package com.lytoyo.neihanduanzi.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.file.Path;

// CosService.java
@Service
public class CosService {
    @Autowired
    private COSClient cosClient;
    
    @Value("${cos.bucketName}")
    private String bucketName;

    public String uploadImage(String objectKey, Path imagePath) throws Exception {
        PutObjectRequest request = new PutObjectRequest(
                bucketName,
                objectKey,
                imagePath.toFile()
        );

        // 关键设置：允许公开访问（根据需求选择是否设置）
        request.setCannedAcl(CannedAccessControlList.PublicRead);

        cosClient.putObject(request);

        // 返回生成的可访问URL
        return generateImageUrl(objectKey);
    }

    // CosService.java 新增方法
    public String generateImageUrl(String objectKey) {
        // 基础URL格式：https://{BucketName}.cos.{Region}.myqcloud.com/{ObjectKey}
        String bucketName = this.bucketName;
        String region = cosClient.getClientConfig().getRegion().getRegionName();

        return String.format("https://%s.cos.%s.myqcloud.com/%s",
                bucketName,
                region,
                objectKey.replace(" ", "%20")); // 处理空格等特殊字符
    }
}